package org.jbch.shittim;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Binder;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class BackgroundAudioService extends Service {
	 
	 //인텐트 액션값으로, 현재 서비스를 시작하고 종료하기 위한 식별문자열입니다. 
	    static final String ACTION_BACKGROUND = "com.example.android.apis.BACKGROUND";
	    static final String ACTION_BASE_INFO_DBSAVE = "org.jbch.shittim.base.info.DBSAVE";
	    static final String ACTION_BASE_INFO_CALL = "org.jbch.shittim.base.info.CALL";
	    static final String ACTION_BROAD_PLAY = "com.example.android.apis.PLAY";
	    static final String ACTION_BROAD_PLAY_ON_LIST = "com.example.android.apis.PLAY_ON_LIST";
	    static final String ACTION_BROAD_PLAY_STATE = "com.example.android.apis.PLAY_STATE";
	    static final String ACTION_BROAD_NEXT = "com.example.android.apis.NEXTPLAY";
	    static final String ACTION_BROAD_PREV = "com.example.android.apis.PREVPLAY";
	    static final String ACTION_BASE_INFO_PARSING_END = "com.example.android.apis.BASE_INFO_PARSING_END";
	    static final String ACTION_NETWORK_STATE_INFO = "com.example.android.apis.NETWORK_STATE_INFO";
	    
	    static final String ACTION_PROGRESS_MAX_VALUE = "com.example.android.apis.PROGRESS_MAX_VALUE";
	    static final String ACTION_PROGRESS_BAR_SHOW = "com.example.android.apis.PROGRESS_PROGRESS_BAR_SHOW";
	    static final String ACTION_PROGRESS_BAR_HIDDEN = "com.example.android.apis.PROGRESS_PROGRESS_BAR_HIDDEN";

		int[] removeItem;	//=new int[100];
			
		private String LOG_TAG = "jbchLog";
	    private ArrayList<HashMap<String, String>> list;
	    private HashMap<String, String> map;
		private List<ShittimInfo> shittimInfo;
		Handler handler;
		Handler phandler;
		MediaPlayer mp;

	    private boolean wasPlaying;
//	    private int mServiceStartId = -1;
		int mIdx;
//		private int currentPosition;
	    
	    
	    // mStartForeground / mStopForeground 리플렉션 메소드의 인자값을 정의한 내용
	    private static final Class[] mStartForegroundSignature = new Class[] {
	        int.class, Notification.class};
	    private static final Class[] mStopForegroundSignature = new Class[] {
	        boolean.class};
	    
	    // 알림관리자
	    private NotificationManager mNM;
	    
	    /*
	     * 서비스를 포그라운드 / 백그라운드로 시작하기 위해서 호출하는 메소드는 다음과 같습니다.
	     * setForeground(true) - 포그라운드 서비스로 시작..
	     * setForeground(false) - 백그라운드 서비스로 시작..
	     * 
	     * 그런데 위의 메소드는 현재 안드로이드 버전에서는 startForeground / stopForeground
	     * 메소드로 변경되었습니다. 그래서 이전 버전의 setForeground 메소드와 startForeground
	     * 메소드를 모두 처리를 하려면, 리플렉션 기술을 사용하여 메소드 변수인 mStartForeground 와
	     * mStopForeground 에 위의 두 메소드중에서 현재 버전에 맞는 메소드를 셋팅해서,
	     * 동적으로 호출하게 됩니다. 그러면 버전에 상관없이 맞는 메소드를 골라서 호출하게 됩니다.
	     */
	    private Method mStartForeground;
	    private Method mStopForeground;
	    private Object[] mStartForegroundArgs = new Object[2];
	    private Object[] mStopForegroundArgs = new Object[1];
	    
	    

		public class BackgroundAudioServiceBinder extends Binder {
			BackgroundAudioService getService() {
				return BackgroundAudioService.this;  
			}
		}

		private final IBinder basBinder = new BackgroundAudioServiceBinder();


	    void startForegroundCompat(int id, Notification notification) {
	      
	        if (mStartForeground != null) {
	            mStartForegroundArgs[0] = Integer.valueOf(id);
	            mStartForegroundArgs[1] = notification;
	            try {
	                mStartForeground.invoke(this, mStartForegroundArgs);
	            } catch (InvocationTargetException e) {
	            } catch (IllegalAccessException e) {
	            }
	            return;
	        }
	        
	        startForeground(id, notification);
	    }
	    
	    /**
	     * This is a wrapper around the new stopForeground method, using the older
	     * APIs if it is not available.
	     * 메소드를 종료 합니다. 위의 startForegroundCompat 메소드와 마찬가지로
	     * mStopForeground 변수에 신규버전의 stopForeground 메소드가 없으면
	     * 이전 버전인 setForeground(false); 메소드를 호출해서,
	     * 알림과 서비스를 종료시킵니다.
	     */
	    void stopForegroundCompat(int id) {
	     
	        // If we have the new stopForeground API, then use it.
	     // stopForeground 메소드가 존재하면 호출해서 종료하고,
	     // 존재하지 않으면 밑에 구버전의 setForeground(false); 메소드로
	     // 현재 서비스를 종료하게 됩니다.
	        if (mStopForeground != null) {
	            mStopForegroundArgs[0] = Boolean.TRUE;
	            try {
	                mStopForeground.invoke(this, mStopForegroundArgs);
	            } catch (InvocationTargetException e) {
	                // Should not happen.
	                Log.w("ApiDemos", "Unable to invoke stopForeground", e);
	            } catch (IllegalAccessException e) {
	                // Should not happen.
	                Log.w("ApiDemos", "Unable to invoke stopForeground", e);
	            }
	            return;
	        }
	        
	        // Fall back on the old API.  Note to cancel BEFORE changing the
	        // foreground state, since we could be killed at that point.
	        // 알림종료
	        mNM.cancel(id);
	        
	        // 서비스종료
	        stopForeground(false);
	    }
	    
	    @Override
	    public void onCreate() {
	    	Log.e(LOG_TAG , "service-onCreate");
		    handler = new Handler();
		    phandler = new Handler();
			list = new ArrayList<HashMap<String, String>>();
			shittimInfo = new ArrayList<ShittimInfo>();
			mIdx = 0;
//			parsingEnd = false;

			mp = new MediaPlayer();
			mp.setOnCompletionListener(mOnCompete);
			mp.setOnSeekCompleteListener(mOnSeekComplete);
			mp.setOnErrorListener(mOnError);
			mp.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
			mp.setOnPreparedListener(mOnPreparedListener);
			mp.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
			
	        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	        try {
	            mStartForeground = getClass().getMethod("startForeground",
	                    mStartForegroundSignature);
	            mStopForeground = getClass().getMethod("stopForeground",
	                    mStopForegroundSignature);
	        } catch (NoSuchMethodException e) {
	            // Running on an older platform.
	            mStartForeground = mStopForeground = null;
	        }
	        
	    }
	    @Override
	    public void onDestroy() {

	        mp.release();
	        mp = null;
	        
	        
	        Log.e(LOG_TAG,"service-onDestory() 호출");
	        
	        
	        
	        // Make sure our notification is gone.
	     // 서비스를 종료합니다. 
	        stopForegroundCompat(R.string.foreground_service_started2);
	    }

	    // This is the old onStart method that will be called on the pre-2.0
	    // platform.  On 2.0 or later we override onStartCommand() so this
	    // method will not be called.
	    // 이전 버전의 서비스 시작시 호출되는 메소드
	    @Override
	    public void onStart(Intent intent, int startId) {
	        if (intent != null) {
	    		handleCommand(intent);
	        }
	    }
	    // 이후 버전의 서비스 시작시 호출되는 메소드
	    @Override
	    public int onStartCommand(Intent intent, int flags, int startId) {

	        Log.i(LOG_TAG,"service-onStartCommand() 호출- intent :" +intent);
	        
//	        mServiceStartId = startId;
	        
	        if (intent != null) {
	    		handleCommand(intent);
	        }
	        return START_STICKY;  
	        
	    }
	    
	    public void setListRowThumImg(boolean isPlaying , int idx){
	    	

	     	Log.i("jbchLog" , "*************>idx:::::::::::>>>>"+idx);
 
			int resId=R.drawable.on_play;
			if(isPlaying){
				resId=R.drawable.on_play;
			}else{
				resId=R.drawable.on_play_disable;
			}

			Intent intent = new Intent(ACTION_BROAD_PLAY_ON_LIST);   
			intent.putExtra("arryIdx", idx);   // 
			intent.putExtra("resId", resId); 
//			intent.putExtra("id", list.get(idx).get(Utils.KEY_ID));  
//			intent.putExtra("id", shittimInfo.get(idx).getmId());  
			sendBroadcast(intent);
			
	    	
	    }
	    
	    /*
	     * 실제 서비스 시작시에 이 메소드를 호출하여, 넘어온 인텐트의 액션값에 따라서, 
	     * 서비스를 포그라운드 / 백그라운드로 시작하고, 종료하는 등의 처리를 합니다.
	     * 알림 설정도 이곳에서 하고 있습니다.
	     */
	    @SuppressWarnings("deprecation")
		void handleCommand(Intent intent) {
	     	
	     	int networkState=0;
    		if(isOnline()){
				networkState=1;		// onLine 상태
    		}else{
				networkState=0;
    		}
	    	


			Intent ntkIntent = new Intent(ACTION_NETWORK_STATE_INFO);
			ntkIntent.putExtra("networkState",networkState);
			sendBroadcast(ntkIntent);
	     	 
	        /*
	         * 컨트롤 액티비티에서 이 서비스를 시작할때 넘긴 액션값을 비교하여,
	         * 포그라운드 액션을 주었는지, 백그라운드 액션을 주었는지를 체크하여,
	         * 해당 처리를 합니다. 포그라운드를 주고 서비스를 호출하였으면 
	         * 알림을 설정하여, 서비스를 포그라운드로 실행하고,
	         * 백그라운드를 주었으면, 알림을 종료하고 서비스를 종료합니다.
	         */ 
			if(networkState==1){
				
				if (ACTION_BROAD_PLAY.equals(intent.getAction())) {
		            
					// In this sample, we'll use the same text for the ticker and the expanded notification
		            CharSequence text = getText(R.string.foreground_service_started2);
		            // Set the icon, scrolling text and timestamp
		            Notification notification = new Notification(R.drawable.ic_launcher, text,System.currentTimeMillis());
		            // The PendingIntent to launch our activity if the user selects this notification
		            PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, secondActivity.class), 0);
		            // Set the info for the views that show in the notification panel.
		            notification.setLatestEventInfo(this, getText(R.string.local_service_label2), text, contentIntent);
		            
					Intent btnIntent = new Intent(ACTION_BROAD_PLAY_STATE); 
					
			        LoadMedia(mIdx);
	        		if(mp.isPlaying() == false){
	    				btnIntent.putExtra("state", 1);
	    				
	        			mp.start();
	        		}else{
	    				btnIntent.putExtra("state", 0);
	        			mp.pause();
	        		}
					sendBroadcast(btnIntent);
	    	    	wasPlaying = mp.isPlaying();
		            startForegroundCompat(R.string.foreground_service_started2, notification);


					setListRowThumImg(wasPlaying, mIdx);
		            
		        }else if(ACTION_BROAD_NEXT.equals(intent.getAction())){

					wasPlaying = mp.isPlaying();
					mIdx = (mIdx == shittimInfo.size()-1 ? 0:mIdx+1);
					
					mp.reset();
					LoadMedia(mIdx);
					if(wasPlaying){
						mp.start();
					} 

					setListRowThumImg(wasPlaying, mIdx);
		        	
		        }else if(ACTION_BROAD_PREV.equals(intent.getAction())){

					wasPlaying = mp.isPlaying();
					mIdx = (mIdx == 0 ? shittimInfo.size()-1:mIdx-1);
					
					mp.reset();
					LoadMedia(mIdx);
					if(wasPlaying){
						mp.start();
					}

					setListRowThumImg(wasPlaying, mIdx);
		        	
		        }else if (ACTION_BACKGROUND.equals(intent.getAction())) {
		            stopForegroundCompat(R.string.foreground_service_started2);
		        }else{

				    if(shittimInfo.size()>0){
						Intent intent2 = new Intent(ACTION_BASE_INFO_PARSING_END);
						intent2.putExtra("parsingEnd", 2);	// 로딩바 자체를 생성안함
						intent2.putExtra("songListDisp",1);
						sendBroadcast(intent2); 
						networkState=1;
			    	}else{
						Log.i("jbchLog", "*************>isOnline:" + isOnline());
	
						Intent intent2 = new Intent(ACTION_BASE_INFO_PARSING_END);
						intent2.putExtra("parsingEnd", 0);
						intent2.putExtra("songListDisp", 0);
						sendBroadcast(intent2);
						list = new ArrayList<HashMap<String, String>>();
						shittimInfo = new ArrayList<ShittimInfo>();
						initialization();
			    	}

		        }
			}else{
				Toast.makeText(this, "인터넷 연결을 확인해주세요." , Toast.LENGTH_SHORT).show();
			}
			
	    } 
	    

		@Override
		public boolean onUnbind(Intent intent) {
//	        stopSelf(mServiceStartId);
	        Log.e(LOG_TAG,"service-onUnbind() 호출");
//	        parsingEnd = false;
			return super.onUnbind(intent);
			
		}
		
	    
	    @Override
	    public IBinder onBind(Intent intent) {
			return basBinder;
	    }


		public MDSInterface getmBinder() {
			return mBinder;
		}


		//
		private final MDSInterface.Stub mBinder = new MDSInterface.Stub() {
			// 이전 곡 플레이
			public void skipBack() throws DeadObjectException {

			}

			// 다음 곡 플레이
			public void skipForward() throws DeadObjectException {
				
			}

			public void pause() throws DeadObjectException {
				mp.pause();
			}

			public void stop() throws DeadObjectException {
				mp.stop();
			}

			@Override
			public boolean isPlaying() throws RemoteException {
				return mp.isPlaying();
			}

			@Override
			public int getMpCurrentPosition() throws RemoteException {
        		if(mp.isPlaying()){
        			return mp.getCurrentPosition();
        		} 
				return 0;
			}

			@Override
			public int getMpDuration() throws RemoteException {
				return mp.getDuration();
			}

			@Override
			public void setSeekTo(int progress) throws RemoteException {
				
				Log.i("jbchLog","progress:"+progress);
				mp.seekTo(progress);
			}

			@Override
			public void playFile(int position) throws RemoteException { 
				setCurrentMidx(position);
				handleCommand(new Intent(ACTION_BROAD_PLAY));
			}

			@Override
			public void setCurrentMidx(int position) throws RemoteException {
				mIdx = position;				
			}

			@Override
			public int getCurrentMidx() throws RemoteException {
				return mIdx;
			}

			@Override
			public void reset() throws RemoteException {
				mp.reset();
			}

			@Override
			public void start() throws RemoteException {
				mp.start();
			}

//			@Override
//			public boolean isPlayingListExit() throws RemoteException {
//
//				//재생 목록 존재 여부
//				if(list.size()>0){		// 재생 목록이 있을 경우
//					return true;
//					
//				}else{					// 재생 목록이 없을 경우
//					return false;
//					
//				}
//			}
		};

//		public ArrayList<HashMap<String, String>> playList() throws RemoteException {
//			return list;
//		}
		

		public List<ShittimInfo> playList() throws RemoteException {
			return shittimInfo;
		}
		
		public boolean isWasPlaying() {
			return wasPlaying;
		}

//		public void setWasPlaying(boolean wasPlaying) {
//			this.wasPlaying = wasPlaying;
//		}


		// 재생 완료면 다음곡으로 
		MediaPlayer.OnCompletionListener mOnCompete= new MediaPlayer.OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {

				// 마지막 곡이면 처음 곡으로 이동
//				mIdx = (mIdx == list.size() -1?0:mIdx+1);
				mIdx = (mIdx == shittimInfo.size() -1?0:mIdx+1);
				//shittimInfo
				mp.reset();
				LoadMedia(mIdx);
				mp.start();

    	    	wasPlaying = mp.isPlaying();
				setListRowThumImg(wasPlaying, mIdx);
			}
		};

		// 위치 이동 완료
		MediaPlayer.OnSeekCompleteListener mOnSeekComplete = new MediaPlayer.OnSeekCompleteListener() {
			
			@Override
			public void onSeekComplete(MediaPlayer mp) {

				if(wasPlaying){
					mp.start();
				}
				
			}
		};

		
		//에러 발생시 메시지 출력
		OnErrorListener mOnError=new OnErrorListener() {
			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {

				String errTxt = "OnError occured.what="+what +",extra="+extra;
				Toast.makeText(BackgroundAudioService.this, errTxt , Toast.LENGTH_SHORT).show();
				return false;
			}
		};

		OnVideoSizeChangedListener mOnVideoSizeChangedListener = new OnVideoSizeChangedListener() {
			
			@Override
			public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
				// TODO Auto-generated method stub
				
			}
		};

		OnPreparedListener mOnPreparedListener =new OnPreparedListener() {
			
			@Override
			public void onPrepared(MediaPlayer mp) {
				// TODO Auto-generated method stub
				
			}
		};
		OnBufferingUpdateListener mOnBufferingUpdateListener = new OnBufferingUpdateListener() {
			
			@Override
			public void onBufferingUpdate(MediaPlayer mp, int percent) {
				// TODO Auto-generated method stub
				
			}
		};
		private boolean Prepare() {

			try {
				mp.prepare();
			} catch (IllegalStateException e) {
				return false;
			} catch (IOException e) {
				return false;
			}
			
			return true;
		}

//		private void setPlayAudioTitle(){
//			String playTitle = list.get(mIdx).get("title");
////			mTitle.setText(playTitle);
//		}
		

		private boolean LoadMedia(int idx) {
//			Uri uri = Uri.parse(list.get(idx).get(Utils.KEY_MP3));
			Uri uri = Uri.parse(shittimInfo.get(idx).getFilename());

			try {
				mp.setDataSource(this,uri);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
			
			if(Prepare()==false){
				return false;
			}
			Intent intent = new Intent(ACTION_PROGRESS_MAX_VALUE); 
			intent.putExtra("mpMaxVal", mp.getDuration());
			sendBroadcast(intent);
			
			return true;
		}
		
		
//		public boolean checkNetwork(){
//			
//
//			ConnectivityManager cManager;
//			NetworkInfo mobile;
//			NetworkInfo wifi;
//			cManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//			mobile = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
//			wifi = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//			
//			return false;
//		}
		
		private boolean isOnline() { //network 연결 상태 확인
//			  Log.i(TAG , "isOnline()");
			  /*
			  ConnectivityManager connectivityManager = (ConnectivityManager)
			  getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
			  NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
			  boolean connected = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
			  return connected;
			  */
			  boolean connected = false;
			  ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			  State mobile = conMan.getNetworkInfo(0).getState(); //mobile
			  State wifi = conMan.getNetworkInfo(1).getState(); //wifi
			  if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//			   Log.i(TAG , "isOnline() : mobile");
			   connected = true;
			  } else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//			      Log.i(TAG , "isOnline() : wifi");
			      connected = true;
			  }
			  
			  return connected;
			 } 

		private void initialization() {
			
			removeItem =new int[10];
	        
//			ConnectivityManager cManager;
//			NetworkInfo mobile;
//			NetworkInfo wifi;
//			cManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//			mobile = cManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
//			wifi = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

			// 3G 또는 WiFi 에 연결되어 있을 경우
//			if (mobile.isConnected() || wifi.isConnected()) { 
			
				new Thread() {
					public void run() {
						try { 

							XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
							factory.setNamespaceAware(true);
							XmlPullParser xpp = factory.newPullParser();
							InputStream stream = getInputStream(Utils.URL);
							xpp.setInput(stream, "UTF-8");
							int eventType = xpp.getEventType();

							String tag = "";
							boolean inTitle = false; // 제목여부판단
							boolean inDate = false; // 제작일자
							boolean inWriter = false; // 작성자 판단
							boolean inMp3 = false; // mp3 판단
							boolean inId = false; // Id
							boolean inItem = false; // 아이템변경 판단
							boolean inDesc = false; // 설명

							// XML 날짜 형식 변환하기
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 HH시 mm분 ss초");
							Date pubdate = null;
							int aNum=0;
							while ((eventType = xpp.next()) != XmlPullParser.END_DOCUMENT) {
								tag = xpp.getName();
								if (eventType == XmlPullParser.TEXT) {
									// 제목
									if (inItem && inTitle) {

										map.put(Utils.KEY_TITLE, xpp.getText()); 
										if((xpp.getText().indexOf("이용안내")>0) || (xpp.getText().indexOf("공지")>0)){
											removeItem[aNum]=list.size();
											aNum++;
										} 
									}
									// 작성일
									if (inItem && inDate) {
										pubdate = new Date(Date.parse(xpp.getText().split(",")[1]));
										map.put(Utils.KEY_PUBDATE, sdf.format(pubdate));
									}
									// 작성자
									if (inItem && inWriter) {
										map.put(Utils.KEY_WRITER, xpp.getText());
									}
									// mp3
									if (inItem && inMp3) {
										map.put(Utils.KEY_MP3, xpp.getText());
									}
									//설명
									if (inItem && inDesc) {
										map.put(Utils.KEY_DESC, xpp.getText());
									}
									// id
									if (inItem && inId) {
										map.put(Utils.KEY_ID, xpp.getText());
									}

								} else if (eventType == XmlPullParser.START_TAG) {
									// 만약 item으로 시작하는 태그라면
									if (tag.compareTo(Utils.KEY_ITEM) == 0) {
										inItem = true;
										map = new HashMap<String, String>();
									}
									// 만약 title 로 시작하는 태그라면
									if (tag.compareTo(Utils.KEY_TITLE) == 0) {
										inTitle = true;
									}
									if (tag.compareTo(Utils.KEY_PUBDATE) == 0) {
										inDate = true;
									}
									// 작성자
									if (tag.compareTo(Utils.KEY_WRITER) == 0) {
										inWriter = true;
									}
									// mp3
									if (tag.compareTo(Utils.KEY_MP3) == 0) {
										inMp3 = true;
									}
									
									//설명
									if (tag.compareTo(Utils.KEY_DESC) == 0) {
										inDesc = true;
									}
 
									// id
									if (tag.compareTo(Utils.KEY_ID) == 0) {
										inId = true;
									}
								} else if (eventType == XmlPullParser.END_TAG) {
									// 태그가 끝나면
									if (tag.compareTo(Utils.KEY_ITEM) == 0) {
										inItem = false;
										list.add(map);
									}
									if (tag.compareTo(Utils.KEY_TITLE) == 0) {
										inTitle = false;
									}
									if (tag.compareTo(Utils.KEY_PUBDATE) == 0) {
										inDate = false;
									}
									// 작성자
									if (tag.compareTo(Utils.KEY_WRITER) == 0) {
										inWriter = false;
									}
									// mp3
									if (tag.compareTo(Utils.KEY_MP3) == 0) {
										inMp3 = false;
									}
									// 설명
									if (tag.compareTo(Utils.KEY_DESC) == 0) {
										inDesc = false;
									}
									// id
									if (tag.compareTo(Utils.KEY_ID) == 0) {
										inId = false;
									}
								} else {
									throw new Exception(
											"Invalid tag at content parse");
								}
							}
							 
							// 방송과 관련없는 내용의 목록은 null 처리하여 넘긴다.
							for(int i=0 ; i<removeItem.length;i++){
								if(removeItem[i]>0){
									list.set(removeItem[i], null);
								}
							} 

							shittimInfo = new ArrayList<ShittimInfo>();

							for (int i = 0; i < list.size(); i++) {
								if(list.get(i)!=null){
									shittimInfo.add(new ShittimInfo(
											list.get(i).get(Utils.KEY_ID), 
											list.get(i).get(Utils.KEY_TITLE), 
											list.get(i).get(Utils.KEY_WRITER), 
											list.get(i).get(Utils.KEY_PUBDATE), 
											list.get(i).get(Utils.KEY_DESC), 
											list.get(i).get(Utils.KEY_MP3), 
											1000)			// 실제 파일 사이즈를 넣어야 한다.
									);
								}
							}
							
							
							

							handler.post(new Runnable() {
								@Override
								public void run() {
									
									
									Intent intent = new Intent(ACTION_BASE_INFO_PARSING_END);
									intent.putExtra("parsingEnd",1);
									intent.putExtra("songListDisp",1);
									sendBroadcast(intent); 
							    	Log.i(LOG_TAG , "BackgroundAudioService>파싱 끝");
							        
								}
							});

						} catch (Exception e) {
//							Log.i("stlog", e.getMessage());
						}
					}

				}.start();

//			}  

		}
		

		private InputStream getInputStream(String para_url) {
			while (true) {
				try {
					URL url = new URL(para_url);
					URLConnection con = url.openConnection();
					InputStream is = con.getInputStream();
					return is;
				} catch (Exception e) {
//					Log.i("stlog", e.getMessage());
				}
			}
		}
		
}